#include<stdio.h>
#include<unistd.h>
#include<sys/socket.h>
#include<sys/select.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<string.h>
#include<iostream>
#include<map>
#include<sys/types.h>
#include<stdlib.h>
using namespace std;
map<string,string>m;
int max_fd=0;
int main(){
    m.insert(make_pair("hello","你好"));
    m.insert(make_pair("apple","苹果"));
    m.insert(make_pair("banana","香蕉"));
    m.insert(make_pair("orange","橙子"));
    m.insert(make_pair("grape","葡萄"));
  int listen_sockfd=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
  if(listen_sockfd<0){
    perror("socket");
    return 0;
  }
  struct sockaddr_in addr;
  addr.sin_family=AF_INET;
  addr.sin_port=htons(2927);
  addr.sin_addr.s_addr=inet_addr("0.0.0.0");
  int ret= bind(listen_sockfd,(struct sockaddr*)&addr,sizeof(addr));
  if(ret<0){
    perror("bind");
    return 0;
  }
  ret=listen(listen_sockfd,5);
  if(ret<0){
    perror("listen");
    return 0;
  }
  //int new_sockfd =accept(listen_sockfd,NULL,NULL);
  //if(new_sockfd<0){
  //  perror("accept");
  // return 0;
  //}
  fd_set readfds;
  FD_ZERO(&readfds);
  if(listen_sockfd>max_fd){
    max_fd=listen_sockfd;
  }
  FD_SET(listen_sockfd,&readfds);

  while(1){
    fd_set tmp= readfds;
    int ret= select(max_fd+1,&tmp,NULL,NULL,NULL);
    if(ret<0){
      continue;
    }
    int i;
    for(i= 0;i<=max_fd;i++){
      if(FD_ISSET(i,&tmp)){
        if(i==listen_sockfd){
          int new_sockfd= accept(listen_sockfd,NULL,NULL);
          if(new_sockfd<0){
            continue;
          }
          FD_SET(new_sockfd,&readfds);
          if(new_sockfd>max_fd){
            max_fd=new_sockfd;
          }
        }else{
          char buf[1024]={0};
          ssize_t r_size= recv(i,buf,sizeof(buf)-1,0);
          if(r_size<0){
            continue;
          }else if(r_size==0){
            FD_CLR(i,&readfds);
            close(i);
          :  continue;
          
          
          
          }
          string result;
          string s(buf);
          if(m.find(s)==m.end())
          {
            result="Unknow";

          }
          else{
            result=(m.find(s))->second;
            send(i,result.c_str(),sizeof(result),0);

          }
        }
      }  
    }
  }
  close(listen_sockfd);
  return 0;
}
